package jianzhi_offer;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

/**
 * @author: zhouyang
 * @descrpition:
 * @time: 2019-04-10 16:02
 */
public class _58_按之字形顺序打印二叉树 {
    public static void main(String[] args) {
        _58_按之字形顺序打印二叉树 test = new _58_按之字形顺序打印二叉树();
        TreeNode root = new TreeNode(8);
        root.left = new TreeNode(6);
        root.right = new TreeNode(10);
        Object obj =  test.Print(root);
    }

    public ArrayList<ArrayList<Integer>> Print(TreeNode pRoot) {
        ArrayList<ArrayList<Integer>> res = new ArrayList<ArrayList<Integer>>();
        if (pRoot == null) return res;
        LinkedList<TreeNode> queue = new LinkedList<>();
        queue.addFirst(pRoot);
        boolean flag = false;//f 左到右
        while (!queue.isEmpty()) {
            ArrayList<Integer> now = new ArrayList<>();
            int size = queue.size();
            LinkedList<TreeNode> next = new LinkedList<>();
            if (!flag) {
                while (size > 0) {
                    TreeNode node = queue.pollFirst();
                    now.add(node.val);
                    if (node.left != null) next.offerLast(node.left);
                    if (node.right != null) next.offerLast(node.right);
                    --size;
                }
            } else {
                while (size > 0) {
                    TreeNode node = queue.pollLast();
                    now.add(node.val);
                    if (node.right != null) next.offerFirst(node.right);
                    if (node.left != null) next.offerFirst(node.left);
                    --size;
                }
            }
            res.add(now);
            queue = next;
            flag = !flag;
        }
        return res;
    }
}
